package com.education.platform.api.controller.user;

import com.education.platform.api.service.LoginService;
import com.education.platform.api.service.SysDictionaryService;
import com.education.platform.api.service.UserAuthService;
import com.education.platform.api.service.UserBaseService;
import com.education.platform.api.service.entity.LoginSuccessDTO;
import com.education.platform.api.vo.request.LoginCompleteRequestVO;
import com.education.platform.api.vo.request.LoginRequestVO;
import com.education.platform.api.vo.request.LoginThirdPartyCheckRequestVO;
import com.education.platform.api.vo.request.LoginThirdPartyRequestVO;
import com.education.platform.api.vo.response.LoginResponseVO;
import com.education.platform.api.service.common.Validservice;
import com.education.platform.api.vo.response.SysDictionaryResponseVO;
import com.education.platform.common.enums.DicTypeEnum;
import com.education.platform.common.util.BeanUtil;

import com.education.platform.common.util.ValidatorUtils;
import com.education.platform.dao.entity.SysDictionaryDO;
import com.education.platform.dao.entity.UserAuthDO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
* describe: 用户注册及登录
* @author : tomato
* @date: 2020-06-03 09:48:32.966
**/
@RestController
@Api("用户注册登录")
@RequestMapping("userLogin")
@Validated
public class UserLoginController {
	
    private static final Logger LOGGER = LoggerFactory.getLogger(UserLoginController.class);
    
	@Autowired
    private UserBaseService userBaseService;

	@Autowired
    private Validservice validservice;
	@Autowired
    private UserAuthService userAuthService;

	@Autowired
    private LoginService loginService;
    @Autowired
    private SysDictionaryService sysDictionaryService;


    @ApiOperation(value = "手机号注册/登录",notes="手机号注册/登录")
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    public LoginResponseVO login(@RequestBody LoginRequestVO loginRequestVO) {
        //校验手机号参数是否正确
        ValidatorUtils.isMobile(loginRequestVO.getPhone());
        LoginSuccessDTO success = loginService.login(loginRequestVO.getPhone(),
                loginRequestVO.getVerificationCode());
        LoginResponseVO result = BeanUtil.convert(success, LoginResponseVO.class);
        return result;
    }



    @ApiOperation(value = "完善登录信息（选择年级和地区）",notes="完善登录信息（选择年级和地区）")
    @RequestMapping(value = "/complete", method = RequestMethod.POST)
    @ResponseBody
    public boolean complete(@RequestBody @Valid LoginCompleteRequestVO completeRequestVO) {
        LoginSuccessDTO success = loginService.complete( completeRequestVO);
        return true;
    }


    @ApiOperation(value = "第三方登录，如果是首次绑定，返回的用户信息为空（token为空），需要认证手机号，调用thirdPartyLoginAuth接口 / 否则直接返回登录用户信息 ",notes="手机号登录")
    @RequestMapping(value = "/thirdPartyLoginCheck", method = RequestMethod.POST)
    @ResponseBody
    public LoginResponseVO thirdPartyLoginCheck(@RequestBody LoginThirdPartyCheckRequestVO checkRequestVO) {
        UserAuthDO authQuery=new UserAuthDO();
        authQuery.setThirdKey(checkRequestVO.getThirdKey());
        authQuery.setThirdType(checkRequestVO.getThirdType());
        UserAuthDO authDO = userAuthService.get(authQuery);
        LoginResponseVO result;
        if(authDO == null){
            //没有绑定过第三方登录   对象属性返回空值。
            result = new LoginResponseVO();
        }else{
            LoginSuccessDTO success = loginService.login(authDO.getUserId());
            result = BeanUtil.convert(success, LoginResponseVO.class);
        }
        return result;

    }

    @ApiOperation(value = "第三方登录并认证手机号完善信息",notes="第三方登录并认证手机号完善信息")
    @RequestMapping(value = "/thirdPartyLoginAuth", method = RequestMethod.POST)
    @ResponseBody
    public LoginResponseVO thirdPartyLoginAuth(@RequestBody LoginThirdPartyRequestVO loginRequestVO) {
        //校验手机号参数是否正确
        ValidatorUtils.isMobile(loginRequestVO.getPhone());
        LoginSuccessDTO success = loginService.login(loginRequestVO);
        LoginResponseVO result = BeanUtil.convert(success, LoginResponseVO.class);
        return result;
    }


    @ApiOperation(value = "退出登录",notes="退出登录")
    @RequestMapping(value = "/logout", method = RequestMethod.POST)
    @ResponseBody
    public void logout(HttpServletRequest request) {
        loginService.logout();
    }



    @ApiOperation(value = "获取年级")
    @PostMapping("selectGrade")
    public Map<String, List<SysDictionaryResponseVO>> selectGrade() {
        Map<String,List<SysDictionaryResponseVO>> map = new HashMap<>(2);
        List<String> typeCodes = Arrays.asList(DicTypeEnum.MIDDLE_GRADE_REGISTER.getValue(), DicTypeEnum.HIGH_GRADE.getValue());
        List<SysDictionaryDO> dictionaryDTOS = sysDictionaryService.getListByDicTypeCodeList(typeCodes);
//        dictionaryDTOS.parallelStream().forEach(m->{
//            if(DicTypeEnum.MIDDLE_GRADE.getValue().equals(m.getTypeCode())){
//
//            }
//        });
        List middles =  dictionaryDTOS.parallelStream().filter(m->DicTypeEnum.MIDDLE_GRADE_REGISTER.getValue().equals(m.getTypeCode())).collect(Collectors.toList());
        List highs =  dictionaryDTOS.parallelStream().filter(m->DicTypeEnum.HIGH_GRADE.getValue().equals(m.getTypeCode())).collect(Collectors.toList());

        middles = BeanUtil.convert(middles,SysDictionaryResponseVO.class);
        highs = BeanUtil.convert(highs,SysDictionaryResponseVO.class);

        map.put(DicTypeEnum.MIDDLE_GRADE_REGISTER.getDes(),middles);
        map.put(DicTypeEnum.HIGH_GRADE.getDes(),highs);
        return map;
    }
}
